import json
import re

from django import http
from django.core.cache import cache
from django.shortcuts import render
import logging
# Create your views here.
from django.views import View

from areas import times
from areas.models import Areas
from meiduo_mall.utils.response_code import RETCODE
from meiduo_mall.utils.view import LoginRequiredMixin
from users.models import Address

logger = logging.getLogger('django')


class Addresses(LoginRequiredMixin, View):
    def get(self, request):
        addresses = Address.objects.filter(user=request.user, is_deleted=False)

        address_dict_list = []
        for address in addresses:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }

            default_address = request.user.default_address
            if default_address.id == address.id:
                address_dict_list.insert(0, address_dict)
            else:
                address_dict_list.append(address_dict)

        context = {
            'default_address_id': request.user.default_address_id,
            'addresses': address_dict_list
        }

        return render(request, 'user_center_site.html', context)


class AddressesView(View):
    def get(self, request):
        sheng_list = cache.get('sheng_list')
        if not sheng_list:

            try:
                addresses = Areas.objects.filter(parent__isnull=True)

                sheng_list = []
                for address in addresses:
                    sheng_list.append({'id': address.id,
                                       'name': address.name})

                cache.set('sheng_list', sheng_list, times.onehour)

            except Exception as e:
                logger.error(e)
                return http.JsonResponse({'code': RETCODE.DBERR,
                                          'errmsg': '查询省份出错'})

        return http.JsonResponse({'code': RETCODE.OK,
                                  'errmsg': 'ok',
                                  'province_list': sheng_list})


class ShiQuAddressView(View):
    def get(self, request, pk):
        subs_data = cache.get('subs_data' + pk)

        if not subs_data:
            try:
                shiqu_all = Areas.objects.filter(parent=pk)
                sheng = Areas.objects.get(id=pk)

                shiqu_list = []
                for shiqu in shiqu_all:
                    shiqu_list.append({'id': shiqu.id,
                                       'name': shiqu.name})

                subs_data = {'id': pk,
                             'name': sheng.name,
                             'subs': shiqu_list}

                cache.set('subs_data' + pk, subs_data, times.onehour)

            except Exception as e:
                logger.error(e)
                return http.JsonResponse({'code': RETCODE.DBERR,
                                          'errmsg': '市区查询错误'})

        return http.JsonResponse({'code': RETCODE.OK,
                                  'errmsg': 'ok',
                                  'sub_data': subs_data})


class AddressPostView(LoginRequiredMixin, View):
    def post(self, request):
        # counts = request.user.addresses.model.objects.filter(is_deleted=False).count()
        # if counts >= 20:
        #     return http.JsonResponse({'code': RETCODE.THROTTLINGERR,
        #                               'errmsg': '地址数量已到达上线'})
        #
        # json_dict = json.loads(request.body.decode())
        # receiver = json_dict.get('receiver')
        # province_id = json_dict.get('province_id')
        # city_id = json_dict.get('city_id')
        # district_id = json_dict.get('district_id')
        # place = json_dict.get('place')
        # mobile = json_dict.get('mobile')
        # tel = json_dict.get('tel')
        # email = json_dict.get('email')
        #
        # if not all([receiver, province_id, city_id, district_id, place, mobile]):
        #     return http.HttpResponseForbidden('缺少必要参数')
        #
        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return http.HttpResponseForbidden('手机号格式错误')
        #
        # if tel:
        #     if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
        #         return http.HttpResponseForbidden('固定电话格式错误')
        #
        # if email:
        #     if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
        #         return http.HttpResponseForbidden('邮箱格式错误')
        #
        # try:
        #     address = Address.objects.create(
        #         user=request.user,
        #         province_id=province_id,
        #         city_id=city_id,
        #         district_id=district_id,
        #         title=receiver,
        #         receiver=receiver,
        #         place=place,
        #         mobile=mobile,
        #         tel=tel,
        #         email=email
        #     )
        #     if not request.user.default_address:
        #         request.user.default_address = address
        #         request.user.save()
        #
        # except Exception as e:
        #     logger.error(e)
        #     return http.JsonResponse({'code': RETCODE.DBERR,
        #                               'errmsg': '地址存储错误'})
        #
        # address_dict = {
        #     "id": address.id,
        #     "title": address.title,
        #     "receiver": address.receiver,
        #     "province": address.province.name,
        #     "city": address.city,
        #     "district": address.district.name,
        #     "place": address.place,
        #     "mobile": address.mobile,
        #     "tel": address.tel,
        #     "email": address.email
        # }
        #
        # return http.JsonResponse({'code': RETCODE.OK,
        #                           'errmsg': 'ok',
        #                           'address': address_dict})

        count = request.user.addresses.model.objects.filter(is_deleted=False).count()
        if count >= 20:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR,
                                      'errmsg': '地址个数超过'})

        # 2.接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 3.检验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('手机号格式不正确')

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')

        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        # 4.保存参数mysql
        try:
            address = Address.objects.create(
                user=request.user,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                title=receiver,
                receiver=receiver,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )

            # 5.判断是否有默认地址, 如果没有增加
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            logger.error(e)

            return http.JsonResponse({'code': RETCODE.DBERR,
                                      'errmsg': '数据库保存错误'})

        # 6.组织参数
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 7.返回json
        return http.JsonResponse({'code': RETCODE.OK,
                                  'errmsg': 'ok',
                                  'address': address_dict})


class UpdateDeleteAddressView(LoginRequiredMixin, View):
    def put(self, request, address_id):
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.HttpResponseForbidden('缺少必传参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden('参数mobile有误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.HttpResponseForbidden('参数tel有误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.HttpResponseForbidden('参数email有误')

        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR,
                                      'errmsg': '更新地址失败'})

        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return http.JsonResponse({'code': RETCODE.OK,
                                  'errmsg': '更新地址成功',
                                  'address': address_dict})

    def delete(self, request, address_id):
        try:
            address = Address.objects.get(id=address_id)

            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '删除地址失败'})

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除地址成功'})


class DefaultView(View):
    def put(self, request, address_id):
        try:
            address = Address.objects.get(id=address_id)

            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置默认地址失败'})

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '设置默认地址成功'})


class TitleView(View):
    def put(self, request, address_id):
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')

        try:
            address = Address.objects.get(id=address_id)

            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': '设置地址标题失败'})

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})
